import time
import os
from typing import overload


class AlterImport:
    """
    将import 修改为try expect

    import os
    try:
        import requests
    except Exception as e:
        print(e.args)
        str = 'pip install requests'
        os.system(str)



        输入：path
            -> 判断 ： 当仅为一个路径时（is str） 执行alter_file 替换
                        当为路径列表时(is list) 执行alter_file_list 替换
        输出：文件




        函数：
        __init__ :初始化
        alter_condition : 替换的条件
        alter_file :替换文件
        alter_file_list: 替换多个文件（输入为文件列表）
        auto_alter_import: 替换文件（整合 alter_file alter_file_list）
        insert_str: 将以前的语句 替换成 这个语句
    """

    def __init__(self, path=''):
        '''
        初始化路径
        :param path:
        '''

        self.path = path
        self.lib = ''
        self.line = ''
        self.words = []

    def insert_str(self, line: str) -> str:
        '''
        插入并替换之前的import
        :param line:
        :return:
        '''
        count_spaces = line.index(self.words[0])
        position = ' ' * count_spaces
        insert_str_try = position + 'try : ' + line.strip()
        pip_install = 'pip install ' + self.lib
        insert_str_except = position + 'except ModuleNotFoundError : os.system(\'' + pip_install + '\')'
        str = insert_str_try + '\n' + insert_str_except + '\n'
        return str

    def alter_condition(self, key) -> bool:
        '''
        判断是否执行替换
        :param key:
        :return:
        '''
        if key == 'import' or \
                key == 'from':
            return True

    def alter_file(self, path: str):
        '''
        替换文件
        :param path:
        :return:
        '''
        t = int(time.time())
        tmp = path + str(t)  # this will be deleted
        os.renames(path, tmp)  # rename
        with open(tmp, 'r') as f_r:
            with open(path, 'w+') as f_w:
                f_w.write('import os\n')
                lines = f_r.readlines()
                for line in lines:
                    self.words = line.strip().split()
                    key = self.words[0]
                    if self.alter_condition(key):
                        self.lib = self.words[1]
                        line = self.insert_str(line)
                    f_w.write(line)
        os.remove(tmp)

    def alter_file_list(self, path: list):
        '''
        替换文件列表
        :param path:
        :return:
        '''
        for i in path:
            self.alter_file(i)

    def auto_alter_import(self):
        '''
        根据输入的路径的 类型 执行对应的替换
        如：路径的类型为 str（仅一个py文件） 执行 alter_file
        路径类型为 list 执行 alter_file_list
        :return:
        '''
        path = self.path
        tp = type(path)
        if tp is str:
            self.alter_file(path)
        elif tp is list:
            self.alter_file_list(path)


if __name__ == '__main__':
    # # AlterImport('test.py').alter_import()
    ls = ['test.py', 'test1.py']
    # AlterImport(ls).auto_alter_import()
    AlterImport().alter_file_list('test.py')
